import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/providers/auth_provider.dart';
import '../../../core/providers/user_extra_info_provider.dart';

class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends ConsumerState<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoading = false;
  bool _isPasswordVisible = false;

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 基于屏幕宽度的自适配缩放（仅在小屏缩小，不在大屏放大）
    const double designWidth = 390.0;
    final double deviceWidth = MediaQuery.of(context).size.width;
    final double scale = (deviceWidth / designWidth).clamp(0.80, 1.0);
    return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(20.0),
          child: Form(
            key: _formKey,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight:
                    MediaQuery.of(context).size.height -
                    MediaQuery.of(context).padding.top -
                    MediaQuery.of(context).padding.bottom -
                    48, // 减去padding
              ),
              child: IntrinsicHeight(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    SizedBox(height: 24 * scale),
                    // Logo和标题
                    _buildHeader(scale),
                    SizedBox(height: 24 * scale),
                    // 登录表单
                    _buildLoginForm(scale),
                    SizedBox(height: 24 * scale),
                    // 登录按钮
                    _buildLoginButton(),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(double scale) {
    return Column(
      children: <Widget>[
        Container(
          width: 70 * scale,
          height: 70 * scale,
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.primary,
            borderRadius: BorderRadius.circular(18),
          ),
          child: Icon(Icons.school, color: Colors.white, size: 30 * scale),
        ),
        SizedBox(height: 16 * scale),
        Text(
          'AI学习助手',
          style: Theme.of(
            context,
          ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 4 * scale),
        Text(
          '智能辅导，高效学习',
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
            color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
          ),
        ),
      ],
    );
  }

  Widget _buildLoginForm(double scale) {
    return Column(
      children: <Widget>[
        // 账号输入
        TextFormField(
          controller: _usernameController,
          keyboardType: TextInputType.text,
          decoration: InputDecoration(
            labelText: '账号',
            hintText: '请输入账号',
            prefixIcon: const Icon(Icons.person),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(14)),
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入账号';
            }
            return null;
          },
        ),
        const SizedBox(height: 16),
        // 密码输入
        TextFormField(
          controller: _passwordController,
          obscureText: !_isPasswordVisible,
          decoration: InputDecoration(
            labelText: '密码',
            hintText: '请输入密码',
            prefixIcon: const Icon(Icons.lock),
            suffixIcon: IconButton(
              icon: Icon(
                _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
              ),
              onPressed: () {
                setState(() {
                  _isPasswordVisible = !_isPasswordVisible;
                });
              },
            ),
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(14)),
          ),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '请输入密码';
            }
            return null;
          },
        ),
      ],
    );
  }

  Widget _buildLoginButton() {
    return FilledButton(
      onPressed: _isLoading ? null : _handleLogin,
      style: FilledButton.styleFrom(
        padding: const EdgeInsets.symmetric(vertical: 14),
      ),
      child:
          _isLoading
              ? const SizedBox(
                height: 20,
                width: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              )
              : Text(
                '登录',
                style: Theme.of(context).textTheme.labelLarge?.copyWith(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                ),
              ),
    );
  }

  Widget _buildFooter() {
    return const SizedBox.shrink(); // 移除底部文字
  }

  void _handleLogin() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 打印请求参数
      print('🔐 登录请求参数:');
      print('  账号: ${_usernameController.text}');
      print('  密码: ${_passwordController.text}');

      // 调用登录方法
      await ref
          .read(authProvider.notifier)
          .login(_usernameController.text, _passwordController.text);

      // 获取登录状态和用户额外信息状态
      final authState = ref.read(authProvider);
      final userExtraInfo = ref.read(userExtraInfoProvider);

      if (authState.isFirstLogin ||
          userExtraInfo == null ||
          !userExtraInfo.isComplete) {
        // 首次登录或用户信息不完整，跳转到用户画像初始化
        print('🔄 跳转到完善档案页面');
        if (context.mounted) {
          context.go('/profile-setup');
        }
      } else {
        // 非首次登录且用户信息完整，直接跳转到主页
        print('✅ 用户信息完整，直接进入应用');
        if (context.mounted) {
          context.go('/dashboard');
        }
      }
    } catch (e) {
      print('❌ 登录异常: $e');
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('登录失败：$e')));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
